package handler

import (
	"car-order-sys/cache"
	"car-order-sys/models"
	"car-order-sys/pkg"
	"strconv"
	"time"

	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

func UserList(c *gin.Context) {
	//	SELECT
	//*
	//FROM
	//users
	//LEFT JOIN user_roles ON users.id=user_roles.uid
	uid := c.Query("uid")
	var role []models.Role
	models.DB.Table("roles").
		Joins("LEFT JOIN user_roles ON roles.id=user_roles.uid").
		Where("user_roles.id=?", uid).Find(&role)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "ok",
		"data": role,
	})
	return
}
func RoleList(c *gin.Context) {
	//	SELECT
	//*
	//FROM
	//roles
	//LEFT JOIN role_nodes ON roles.id=role_nodes.rid
	rid := c.Query("rid")
	var node []models.Node
	models.DB.Table("nodes").
		Joins("LEFT JOIN role_nodes ON nodes.id=role_nodes.rid").
		Where("role_nodes.id=?", rid).Find(&node)

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "ok",
		"data": node,
	})
	return
}
func UserRoleAdd(c *gin.Context) {
	uid, _ := strconv.Atoi(c.Query("uid"))
	rid, _ := strconv.Atoi(c.Query("rid"))
	data := models.UserRole{
		Model: gorm.Model{},
		Rid:   rid,
		Uid:   uid,
	}
	err := models.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}
func RoleNodeAdd(c *gin.Context) {
	rid, _ := strconv.Atoi(c.Query("rid"))
	nid, _ := strconv.Atoi(c.Query("nid"))
	data := models.RoleNode{
		Model: gorm.Model{},
		Rid:   rid,
		Nid:   nid,
	}
	err := models.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}
func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不能为空",
		})
		return
	}
	redis_key := "login_" + username
	errCount, _ := cache.Rdb.Get(cache.Ctx, redis_key).Int()
	if errCount >= 3 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误三次禁止登录",
		})
		return
	}
	var user models.User
	err := models.DB.Where("username=?", username).Find(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "查询用户失败",
		})
		return
	}
	if user.ID == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "账号或密码错误",
		})
		return
	}
	if user.Password != pkg.Md5(password) {
		cache.Rdb.Incr(cache.Ctx, redis_key)
		if errCount == 2 {
			cache.Rdb.Set(cache.Ctx, redis_key, 3, time.Hour*2)
			c.JSON(200, gin.H{
				"code": 500,
				"msg":  "密码错误三次封禁2小时",
			})
			return
		}
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "登录成功",
		"data": user,
	})
	return
}
